//
//  Extension+Data.swift
//  SwiftIM
//
//  Created by 汪志浩 on 2022/12/12.
//

import Foundation
import CommonCrypto
public extension Data {
    
    func calculateMd5()->String{
        
        var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        
#if swift(>=5.0)
        
        _ = self.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
            return CC_MD5(bytes.baseAddress, CC_LONG(self.count), &digest)
        }
#else
        _ = self.withUnsafeBytes { bytes in
            return CC_MD5(bytes, CC_LONG(data.count), &digest)
        }
#endif
        return digest.map { String(format: "%02x", $0) }.joined()
    }
    
    /**异步计算 md5**/
    static func calculateMd5(url:String? , complete:((_ md5:String?)->())?){
        guard let url = url else {
            complete?(nil)
            return
        }
        DispatchQueue.global().async {
            do{
                let data = try Data(contentsOf: URL(fileURLWithPath: url))
                let md5 = data.calculateMd5()
                MainThread {
                    complete?(md5)
                }
            }catch let err{
                debugPrint("\(err)")
                complete?(nil)
            }
        }
    }
}
